//条件ID全局变量
var currentId_playback = 0
//layui框架表单容器
var field
//进度条
var PROGRESS_VALUE = 0
//计时器初始化
var hour = 0;
var min = 0;
var sec = 0;
var timer = null;
var playback_time_length = 0;
//协议容器
var proto_select_option = []
//文件类型容器
var filetype_select_option = []
//请求用
var playback_config_request
//表格用
var tablelist = []
//表格类型选择总容器
var all_select_option = [{
	value: "",
	text: "待配置"
}]

$.ajax({
	url: 'http://' + ipm + ':8081/dict/query',
	type: 'POST',
	contentType: 'application/json',
	dataType: 'json',
	data: {},
	success: function (response) {
		localplaybackConfigRead(response)
		var dm8data = response.data;
		var dm8content = dm8data.content;
		var datalist = [];
		var testa;
		var testb;
		for (var i = 0; i < dm8content.length; i++) {
			// if (dm8content[i].cfgType == 4) {
			// 	datalist[i] = dm8content[i].content;
			// 	testa = JSON.parse(datalist[i]);
			// 	testb = testa.protocols;
			// 	for (var j = 0; j < testb.length; j++) {
			// 		proto_name = "协议-" + testb[j].name
			// 		proto_select_option.push(proto_name)
			// 		selectObj = {
			// 			value: "",
			// 			text: ""
			// 		}
			// 		selectObj.value = proto_name
			// 		selectObj.text = proto_name
			// 		all_select_option.push(selectObj)
			// 	}
			// }
			if (dm8content[i].cfgType == 6) {
				datalist[i] = dm8content[i].content;
				testa = JSON.parse(datalist[i]);
				testb = testa.type_defines;
				for (var j = 0; j < testb.length; j++) {
					filetype_select_option.push(testb[j])
					selectObj = {
						value: "",
						text: ""
					}
					selectObj.value = testb[j]
					selectObj.text = testb[j]
					all_select_option.push(selectObj)
				}
			}
		}
		console.log(all_select_option)
		bootstrapTable_init();
		// console.log(proto_select_option);
		// console.log(filetype_select_option);
	}
});



//播放
function data_playback_play(datap) {
	var Play = playback_config_request.local

	startJson = {
		"cmd_code": "start",
		// "ctrl_id": "127.0.0.1:1234",
		"file_node": "172.16.15.46",
		"start": {
			"time_range": ["2023-11-15 10:00:00", "2023-11-15 10:10:00"],
			"speed": 1,
			"data": ""
		}
	}
	// startJson.ctrl_id = field.control_ip + ":" + field.control_port;
	startJson.file_node = field.storage_ip;
	start_and_end = []
	start_and_end.push(field.laydate_startTime)
	start_and_end.push(field.laydate_endTime)
	startJson.start.time_range = start_and_end;
	startJson.start.speed = parseInt(datap[0].value);
	startJson.start.data = Play;
	console.log(startJson)
	var startWeb = JSON.stringify(startJson) + " "

	$.ajax({
		url: 'http://' + ipm + ':8085',
		type: 'POST',
		data: startWeb,
		success: function (response) {
			console.log(response);
		}
	});


}


//继续
function data_playback_continue() {

	var continueJson = {
		"cmd_code": "continue",
		"magic_number": 1234
	}
	var continueWeb = JSON.stringify(continueJson) + " "

	$.ajax({
		url: 'http://' + ipm + ':8085',
		type: 'POST',
		data: continueWeb,
		success: function (response) {
			console.log(response);
		}
	});
}

//暂停
function data_playback_pause() {

	var pauseJson = {
		"cmd_code": "pause",
		"magic_number": 1234
	}
	var pauseWeb = JSON.stringify(pauseJson) + " "

	$.ajax({
		url: 'http://' + ipm + ':8085',
		type: 'POST',
		data: pauseWeb,
		success: function (response) {
			console.log(response);
		}
	});
}

//结束
function data_playback_stop() {
	var stopJson = {
		"cmd_code": "stop",
		"magic_number": 1234
	}
	var stopWeb = JSON.stringify(stopJson) + " "
	$.ajax({
		url: 'http://' + ipm + ':8085',
		type: 'POST',
		data: stopWeb,
		success: function (response) {
			console.log(response);
		}
	});
}


//变速
function data_playback_speed() {
	$.ajax({
		url: 'http://' + ipm + ':8085',
		type: 'POST',
		data: nodeTypeSTORAGEWeb,
		success: function (response) {
			console.log(response);
		}
	});
}



//条件配置
function bootstrapTable_init() {
	$("#bootstrap-table").bootstrapTable('destroy').bootstrapTable({
		data: tablelist,
		dataType: 'json',
		pagination: true,                   //是否显示分页（*）
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		sortOrder: "asc",                   //排序方式
		sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
		pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
		pageSize: 10,                     //每页的记录行数（*）
		pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
		strictSearch: true,
		minimumCountColumns: 1,             //最少允许的列数
		uniqueId: "id",                     //每一行的唯一标识，一般为主键列
		onEditableSave: onEditableSave,
		columns: [{
			field: 'ID',
			align: 'center',
			title: '序号',
			width: 60,
			formatter: function (value, row, index) {
				return index + 1;
			}
		}, {
			field: 'data_type',
			align: 'center',
			title: '数据类型',
			editable: {
				type: 'select',
				title: '值类型',
				source: all_select_option
			}
		}, {
			field: 'space',
			align: 'center',
			title: '数据空间',
			editable: {
				type: 'select',
				title: '值类型',
				source: [{
					value: "",
					text: "请选择"
				}, {
					value: "空间1",
					text: "空间1"
				}, {
					value: "空间2",
					text: "空间2"
				}
				]
			}
		}, {
			field: 'data_path',
			align: 'center',
			title: '数据目录',
			editable: {
				emptytext: '待配置'
			}
		}, {
			field: 'dest_ip',
			align: 'center',
			title: '回放目的IP',
			editable: {
				emptytext: '待配置'
			}
		}, {
			field: 'dest_port',
			align: 'center',
			title: '回放目的端口',
			editable: {
				type: 'number',
				emptytext: '待配置',
				validate: function (value) {
					// 如果输入的值大于ip最大值，则默认设置为65535
					console.log(parseInt(value))
					if (value != null && value != '' && parseInt(value) > 65535 ) {
						layer.msg('保存失败,输入范围(0,65535)', { icon: 2 });
						return '超出范围';
					}
				}
			}
		}, {
			field: 'id',
			align: 'center',
			title: '删除',
			formatter: function (value, row, index) {
				return "<a href='javascript:;' class='btn btn-xs red' onclick=\"playback_config_modify('" + value + "')\" title='删除'><span class='feather-trash-2'></span></a>";
			}
		}
		]
	});
}


$(function () {
	$("#btn_delete").click(function () {
		hour = 0;
		min = 0;
		sec = 0;
		clearInterval(timer);
		timer = null;
		PROGRESS_VALUE = 0;
		document.getElementById('progress').value = PROGRESS_VALUE;
		$('#showtime span:eq(0)').html('00');
		$('#showtime span:eq(2)').html('00');
		$('#showtime span:eq(4)').html('00');
		data_playback_stop();
		$('#btn_play').show();
		$('#btn_continue').hide();
		$('#btn_pause').hide();
	})

	$("#btn_continue").click(function () {
		//alert("继续")
		timer = setInterval(function () {
			//计时
			sec++;
			if (min == 60) {
				hour++; min = 0;
			}
			if (sec == 60) {
				min++; sec = 0;
			}
			var secStr = sec;
			if (sec < 10) {
				secStr = "0" + sec;
			}
			var minStr = min;
			if (min < 10) {
				minStr = "0" + min;
			}
			var hourStr = hour;
			if (hour < 10) {
				hourStr = "0" + hour;
			}
			if ((hour * 3600 + min * 60 + sec) == playback_time_length) {
				clearInterval(timer);
			}
			$('#showtime span:eq(0)').html(hourStr);
			$('#showtime span:eq(2)').html(minStr);
			$('#showtime span:eq(4)').html(secStr);
			//进度条移动
			PROGRESS_VALUE = 100 / playback_time_length + PROGRESS_VALUE
			// console.log(PROGRESS_VALUE)
			document.getElementById('progress').value = PROGRESS_VALUE;
			if (Math.ceil(PROGRESS_VALUE) >= 100) {
				hour = 0;
				min = 0;
				sec = 0;
				clearInterval(timer);
				timer = null;
				PROGRESS_VALUE = 0
				document.getElementById('progress').value = PROGRESS_VALUE;
				$('#showtime span:eq(0)').html('00');
				$('#showtime span:eq(2)').html('00');
				$('#showtime span:eq(4)').html('00');
				$('#btn_pause').hide();
				$('#btn_continue').hide();
				$('#btn_play').show();
			}
		}, 1000)
		$('#btn_continue').hide();
		$('#btn_pause').show();
	})

	$("#btn_pause").click(function () {
		clearInterval(timer);
		$('#btn_continue').show();
		$('#btn_pause').hide();
	})

});


function isNumberKey(event) {
	var charCode = (event.which) ? event.which : event.keyCode;
	if (charCode != 46 && charCode > 31
		&& (charCode < 48 || charCode > 57) && (charCode < 96 || charCode > 105))
		return false;
	return true;
}

function NumberKey(myIndex) {
	let value = $("#dest_port" + myIndex).val();
	console.log(value)
	// 如果输入的值大于ip最大值，则默认设置为65535
	if (value != null && value != '' && parseInt(value) > 65535) {
		$("#dest_port" + myIndex).val("65535");
		return false;
	}

	// 判断是否是0开头的不规范数字
	if (value != null && value != '' && parseInt(value) != 0) {
		// 如果当前输入的是0开头，则把0去掉,方法是直接转数字即可
		value = parseInt(value);
		if (isNaN(value)) {
			$("#dest_port" + myIndex).val("");
		} else {
			$("#dest_port" + myIndex).val("" + value);
		}
	}
}


//日期选择框渲染
layui.use('form', function () {
	var form = layui.form;
	//方法提交
	$('#btn_play').on('click', function (data) {
		if (timer) {
			console.log("正在播放")
			return false
		}
		form.submit('playbackfield', function (data) { // 注：v2.7.0 新增
			//选择框不可用移除
			$('#bootstrap-table tr').each(function (i) {
				if ($(this).find('td:eq(1) select').val() == "数据库") {
					var select_space = document.getElementById("space" + (i - 1))
					select_space.disabled = false;
					console.log("11")
				}
			});
			// 回调函数返回结果跟上述 submit 事件完全一致
			field = data.field;
			// do something
			console.log(field)
			var datap = $("#form-play").serializeArray();
			var count = $('#bootstrap-table').bootstrapTable('getData').length;
			data_length = count * 5;
			// console.log(data)
			// console.log(datap)
			// console.log(data_length)
			//拆分回放时间
			// console.log(field.laydate_startTime)
			// console.log(field.laydate_endTime)
			startTimeArr = field.laydate_startTime.split(" ")
			endTimeArr = field.laydate_endTime.split(" ")
			startDate = startTimeArr[0].split("-")
			startDatetime = startTimeArr[1].split(":")
			endDate = endTimeArr[0].split("-")
			endDatetime = endTimeArr[1].split(":")

			//比较前后时间，若起始时间比结束时间晚则false
			startLong = parseInt(startDate[0]) * 31536000 + parseInt(startDate[1]) * 2626560 + parseInt(startDate[2]) * 86400 + parseInt(startDatetime[0]) * 3600 + parseInt(startDatetime[1]) * 60 + parseInt(startDatetime[2])
			endLong = parseInt(endDate[0]) * 31536000 + parseInt(endDate[1]) * 2626560 + parseInt(endDate[2]) * 86400 + parseInt(endDatetime[0]) * 3600 + parseInt(endDatetime[1]) * 60 + parseInt(endDatetime[2])
			if (startLong > endLong) {
				layer.msg('回放区间选择错误', { icon: 2 });
				return false;
			}

			//计算回放时长
			playback_time_length = endLong - startLong
			if (playback_time_length > 86400) {
				layer.msg('回放区间不可超过24小时', { icon: 2 });
				return false;
			}
			progress_h = Math.floor(playback_time_length / 3600)
			progress_m = Math.floor((playback_time_length % 3600) / 60)
			progress_s = Math.floor(playback_time_length % 60)
			//秒位显示修正
			if (progress_h < 10) {
				progress_h_show = "0" + progress_h
			}
			else {
				progress_h_show = progress_h
			}
			//秒位显示修正
			if (progress_m < 10) {
				progress_m_show = "0" + progress_m
			} else {
				progress_m_show = progress_m
			}
			//秒位显示修正
			if (progress_s < 10) {
				progress_s_show = "0" + progress_s
			} else {
				progress_s_show = progress_s
			}
			// console.log(progress_s_show)

			progress_time = progress_h_show + " : " + progress_m_show + " : " + progress_s_show
			// console.log(progress_time)
			$("#totalTime").text(progress_time)
			// console.log(data.length)
		
			data_playback_play(datap);

			//选择框不可用启用
			$('#bootstrap-table tr').each(function (i) {
				if ($(this).find('td:eq(1) select').val() == "数据库") {
					var select_space = document.getElementById("space" + (i - 1))
					select_space.disabled = true;
					console.log("22")
				}
			});
			clearInterval(timer);
			// console.log(playback_time_length)
			function foo(playback_time_length) {
				return playback_time_length
			}
			// timer = setInterval(show(progress_h, progress_m, progress_s), 1000)
			timer = setInterval(function () {

				//计时
				playback_time_length = foo(playback_time_length)
				sec++;
				if (min == 60) {
					hour++; min = 0;
				}
				if (sec == 60) {
					min++; sec = 0;
				}
				var secStr = sec;
				if (sec < 10) {
					secStr = "0" + sec;
				}
				var minStr = min;
				if (min < 10) {
					minStr = "0" + min;
				}
				var hourStr = hour;
				if (hour < 10) {
					hourStr = "0" + hour;
				}
				if ((hour * 3600 + min * 60 + sec) == playback_time_length) {
					clearInterval(timer);
				}
				$('#showtime span:eq(0)').html(hourStr);
				$('#showtime span:eq(2)').html(minStr);
				$('#showtime span:eq(4)').html(secStr);

				//进度条移动
				PROGRESS_VALUE = 100 / playback_time_length + PROGRESS_VALUE
				// console.log(PROGRESS_VALUE)
				document.getElementById('progress').value = PROGRESS_VALUE;
				if (Math.ceil(PROGRESS_VALUE) >= 100) {
					hour = 0;
					min = 0;
					sec = 0;
					clearInterval(timer);
					timer = null;
					PROGRESS_VALUE = 0
					document.getElementById('progress').value = PROGRESS_VALUE;
					$('#showtime span:eq(0)').html('00');
					$('#showtime span:eq(2)').html('00');
					$('#showtime span:eq(4)').html('00');
					$('#btn_pause').hide();
					$('#btn_continue').hide();
					$('#btn_play').show();
				}
			}, 1000)

			$('#btn_pause').show();
			$('#btn_play').hide();
		});
		return false;
	});
});




layui.use('laydate', function () {
	var laydate = layui.laydate;
	var startDate = laydate.render({
		elem: '#laydate_startTime',
		// max: $('#laydate_endTime').val(),
		type: 'datetime',
		theme: 'molv',
		trigger: 'click',
		done: function (value, date) {
			// 结束时间大于开始时间

			if (value !== '') {
				endDate.config.min.year = date.year;
				endDate.config.min.month = date.month - 1;
				endDate.config.min.date = date.date;
				endDate.config.min.hours = date.hours;
				endDate.config.min.minutes = date.minutes;
				endDate.config.min.seconds = date.seconds;
			} else {
				endDate.config.min.year = '';
				endDate.config.min.month = '';
				endDate.config.min.date = '';
				endDate.config.min.hours = '';
				endDate.config.min.minutes = '';
				endDate.config.min.seconds = '';
			}
		}
	});

	var endDate = laydate.render({
		elem: '#laydate_endTime',
		min: $('#laydate_startTime').val(),
		type: 'datetime',
		theme: 'molv',
		trigger: 'click',
		done: function (value, date) {
			// 开始时间小于结束时间
			if (value !== '') {
				startDate.config.max.year = date.year;
				startDate.config.max.month = date.month - 1;
				startDate.config.max.date = date.date;
				startDate.config.max.hours = date.hours;
				startDate.config.max.minutes = date.minutes;
				startDate.config.max.seconds = date.seconds;
			} else {
				startDate.config.max.year = '';
				startDate.config.max.month = '';
				startDate.config.max.date = '';
				startDate.config.max.hours = '';
				startDate.config.max.minutes = '';
				startDate.config.max.seconds = '';
			}
		}
	});

});
// }


//新增行
function addRow() {
	var arrPlaybCfg = playback_config_request.local;
	var id = playback_config_request.max_id;
	id++;
	var playbCfgWeb = {
		"cfgType": "8",
		"cfgName": "replay.json",
		"content": ""
	}
	var playbCfgSave = {
		"cfg_type": 8,
		"max_id": "",
		"remote": [],
		"local": []
	}
	if (id) {
		playbCfg = {
			"id": "",
			"data_type": "",
			"space": "",
			"data_path": "",
			"dest_ip": "",
			"dest_port": "",
			"is_protocol": false
		}
		playbCfg.id = id;
	} else {
		arrPlaybCfg = []
		playbCfg = {
			"id": "",
			"data_type": "",
			"space": "",
			"data_path": "",
			"dest_ip": "",
			"dest_port": "",
			"is_protocol": false
		}
		id = 0;
		playbCfg.id = 0;
	}
	arrPlaybCfg.push(playbCfg)
	playbCfgSave.remote = playback_config_request.remote;
	playbCfgSave.local = arrPlaybCfg;
	playbCfgSave.max_id = id;
	playbCfgWeb.content = JSON.stringify(playbCfgSave);
	// console.log(playbCfgSave);
	////////////////////////////////////////////////
	////////////////请求发送并重新建表///////////////
	////////////////////////////////////////////////
	var xhr = new XMLHttpRequest();
	// 配置请求
	xhr.open('POST', 'http://' + ipm + ':8081/dict/save', true);
	xhr.setRequestHeader('content-Type', 'application/json');
	// 发送 JSON 数据
	xhr.send(JSON.stringify(playbCfgWeb));
	// 监听请求的状态
	xhr.onreadystatechange = function () {
		// console.log(xhr.readyState);
		if (xhr.readyState === 4 && xhr.status === 200) {
			// console.log(xhr.responseText);
			$.ajax({
				url: 'http://' + ipm + ':8081/dict/query',
				type: 'POST',
				contentType: 'application/json',
				dataType: 'json',
				data: {},
				success: function (response) {
					tablelist = []
					localplaybackConfigRead(response)
					bootstrapTable_init();
				}
			});
		}
	};
	layer.msg('新增成功', { icon: 1 });
}



//删除行
function playback_config_modify(args) {
	console.log(args)
	var arrPlaybCfg = playback_config_request.local;
	for (var i = 0; i < arrPlaybCfg.length; i++) {
		if (arrPlaybCfg[i].id == args) {
			arrPlaybCfg.splice(i, 1);
			console.log(arrPlaybCfg)

		}
	}
	var playbCfgWeb = {
		"cfgType": "8",
		"cfgName": "replay.json",
		"content": ""
	}

	var playbCfgSave = {
		"cfg_type": 8,
		"max_id": "",
		"remote": [],
		"local": []
	}
	playbCfgSave.local = arrPlaybCfg;
	playbCfgSave.remote = playback_config_request.remote;
	playbCfgSave.max_id = playback_config_request.max_id;
	playbCfgWeb.content = JSON.stringify(playbCfgSave);
	////////////////////////////////////////////////
	////////////////请求发送并重新建表///////////////
	////////////////////////////////////////////////
	var xhr = new XMLHttpRequest();
	// 配置请求
	xhr.open('POST', 'http://' + ipm + ':8081/dict/save', true);
	xhr.setRequestHeader('content-Type', 'application/json');
	// 发送 JSON 数据
	xhr.send(JSON.stringify(playbCfgWeb));
	// 监听请求的状态
	xhr.onreadystatechange = function () {
		// console.log(xhr.readyState);
		if (xhr.readyState === 4 && xhr.status === 200) {
			// console.log(xhr.responseText);
			$.ajax({
				url: 'http://' + ipm + ':8081/dict/query',
				type: 'POST',
				contentType: 'application/json',
				dataType: 'json',
				data: {},
				success: function (response) {
					tablelist = []
					localplaybackConfigRead(response)
					bootstrapTable_init();
				}
			});
		}
	};
	layer.msg('删除成功', { icon: 1 });
}


//编辑保存
function onEditableSave(field, row, rowIndex, oldValue, $el) {
	//alert("字段名：" + field + "，当前值：" + row[field] + "，旧值：" + oldValue + "，顺位：" + rowIndex);
	var data = $("#bootstrap-table").bootstrapTable('getData');
	var objChange = data[rowIndex];
	var idChange = objChange.id;
	console.log(objChange.method)
	var arr = playback_config_request.local;
	var playbCfgWeb = {
		"cfgType": "8",
		"cfgName": "replay.json",
		"content": ""
	}
	var playbCfgSave = {
		"cfg_type": 8,
		"max_id": "",
		"remote": [],
		"local": []
	}
	if (field == "data_type") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				if (row[field].includes("协议-")) {
					arr[i].data_type = row[field].substring(3);
					arr[i].is_protocol = true;
				} else {
					arr[i].data_type = row[field];
					arr[i].is_protocol = false;
				}
			}
		}
	} else if (field == "space") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].space = row[field];
			}
		}
	} else if (field == "data_path") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].data_path = row[field];
			}
		}
	} else if (field == "dest_ip") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].dest_ip = row[field];
			}
		}
	} else if (field == "dest_port") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].dest_port = row[field];
			}
		}
	}
	playbCfgSave.local = arr;
	playbCfgSave.remote = playback_config_request.remote;
	playbCfgSave.max_id = playback_config_request.max_id;
	playbCfgWeb.content = JSON.stringify(playbCfgSave)
	postQuestSave(playbCfgWeb);
	// console.log(playbCfgSave)
	// console.log(playbCfgWeb)
	layer.msg('修改成功', { icon: 1 });
}